<template>
  <div class="edit-resume-page">
    <header>
      <div class="c-block">
        <div class="logo">
          <nuxt-link to="/">
            <img :src="siteConfig.siteLogo" alt="logo" />
          </nuxt-link>
        </div>
        <div class="resume-config">
          <a-dropdown placement="bottomCenter" overlayClassName="custom-dropdown">
            <a class="ant-dropdown-link" style="font-size: 12px;" @click="e => e.preventDefault()">{{ themeStyleName }}<a-icon type="down" style="margin-left: 8px;" /></a>
            <a-menu slot="overlay">
              <a-menu-item
                @click="handleChangeTheme(item)"
                v-for="item in themeList"
                :key="item">
                <p>{{ item }}</p>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
          <a-tooltip placement="left">
            <template slot="title"><p style="font-size: 12px;">主题色</p></template>
            <ColorPicker v-model="themeColor" />
          </a-tooltip>
          <a-button type="primary" @click="handleSaveResume">保存</a-button>
          <HeadAvatar
            :width="28"
            :height="28"
            :to="`/user/${userInfo.id}`"
            :img="userInfo.avatar"
            openTarget="self"
          />
        </div>
      </div>
    </header>
    <div class="content" v-show="requestLoading">
      <a-spin size="large" />
    </div>
    <div class="content" v-show="!requestLoading">
      <div class="modify-block">
        <a-collapse v-model="activeKeys">
          <a-collapse-panel v-for="(item, idx) in editResumeList" :key="item.id">
            <template slot="header">
              <div class="edit-header" @click.stop>
                <a-input v-model="item.title" class="edit-header-input" />
                <div class="right-operate" v-if="item.component !== 'BasicInfo'">
                  <a-icon
                    v-if="idx > 1"
                    @click="handleMoveResumeItem(idx, 'up')"
                    type="arrow-up" />
                  <a-icon
                    v-if="idx !== editResumeList.length - 1"
                    @click="handleMoveResumeItem(idx, 'down')"
                    type="arrow-down" />
                  <a-icon
                    v-if="idx === editResumeList.length - 1"
                    type="plus"
                    @click="handleInsertResumeItem" />
                  <a-icon
                    v-if="editResumeList.length > 2"
                    type="delete"
                    @click="handleDeleteResumeItem(idx)" />
                  <a-switch size="small" v-model="item.visible"></a-switch>
                </div>
              </div>
            </template>
            <component
              :is="item.component"
              v-model="item.data"></component>
          </a-collapse-panel>
        </a-collapse>
      </div>
      <div class="show-block resume-display-content" id="resume-display-content">
        <div class="modal" v-for="item in editResumeList.filter(o => o.visible)" :key="item.id">
          <!-- 基本信息 -->
          <template v-if="item.component === 'BasicInfo'">
            <div class="resume-modal-basic-info">
              <div class="show-resume-header">
                <p class="show-resume-header-title">{{ item.title }}</p>
                <div class="LB-desc0"></div>
                <div class="LB-desc1"></div>
                <div class="LB-desc2"></div>
              </div>
              <div class="resume-content">
                <div class="left-info-list">
                  <div
                    class="info-list-item"
                    v-for="(itemName, index) in item.data.list.slice(0, 2)"
                    :key="index"
                    :class="{ 'resume-name': index === 0, 'resume-job': index === 1 }">
                    <div class="info-list-item__name">{{ itemName.fieldName }}</div>
                    <em>：</em>
                    <div class="info-list-item__value">{{ itemName.fieldValue }}</div>
                  </div>
                  <br />
                  <div
                    class="info-list-item"
                    v-for="(itemName, index) in item.data.list.slice(2)"
                    :key="index + 2">
                    <div class="info-list-item__name">{{ itemName.fieldName }}</div>
                    <em>：</em>
                    <div class="info-list-item__value">{{ itemName.fieldValue }}</div>
                  </div>
                </div>
                <div class="right-avatar" v-if="item.data.showAvatar">
                  <img :src="item.data.avatar" alt="">
                </div>
              </div>
            </div>
          </template>

          <!-- 自定义信息 -->
          <template v-if="item.component === 'OtherInfo'">
            <div class="resume-modal-other-info">
              <div class="show-resume-header">
                <p class="show-resume-header-title">{{ item.title }}</p>
                <div class="LB-desc0"></div>
                <div class="LB-desc1"></div>
                <div class="LB-desc2"></div>
              </div>
              <div class="resume-content"
                v-for="(itemName, index) in item.data.list"
                :key="index">
                <div class="sub-top-title">
                  <div class="label-item"
                    v-for="(iitem, iidx) in itemName.order
                      .split(',')
                      .filter(o => itemName.visibleList.includes(o))
                      .filter(o => itemName[o].length)"
                    :key="iidx">
                    <p v-if="iitem !== 'time'">{{ itemName[iitem] }}</p>
                    <p v-else>{{ `${itemName[iitem][0]} ~ ${itemName.rightNow ? '至今' : itemName[iitem][1]}` }}</p>
                  </div>
                </div>
                <div
                  v-show="itemName.editorHtml.replace(/<p><br><\/p>/gi, '')"
                  class="edit-html-content wangeditor-show-html"
                  v-html="itemName.editorHtml"></div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BasicInfo from './components/BasicInfo'
import OtherInfo from './components/OtherInfo'
import { mapState } from 'vuex'
import '@/static/md/markdown/juejin-wangeditor.min.css'
import ColorPicker from './components/ColorPicker.vue'

export default {
  name: 'EditResumePage',
  components: { BasicInfo, OtherInfo, ColorPicker },
  data () {
    return {
      themeColor: '#255db0',
      activeKeys: [],
      editResumeList: [],
      requestLoading: true,
      themeStyleName: 'theme-1',
      themeList: new Array(8).fill(null).map((_i, index) => {
        return `theme-${index + 1}`
      }),
      resumeId: null
    }
  },

  mounted () {
    this.resumeId = this.$route.params.id
    if (this.resumeId) {
      return this.findUserResume()
    }
    this.loadResumeThemeCss()
    document.documentElement.style.setProperty('--resume-theme-color', this.themeColor)
    this.getResumeJsonTemplate()
  },

  methods: {
    async findUserResume () {
      try {
        const data = await this.$axios.get('/gimishare/api/v1/resume/find')
        const { content, themeColor, themeStyleName } = data.data || {}
        this.editResumeList = JSON.parse(content)
        this.themeColor = themeColor
        this.themeStyleName = themeStyleName
        this.activeKeys = this.editResumeList.map(o => o.id)
        await this.loadResumeThemeCss()
        document.documentElement.style.setProperty('--resume-theme-color', themeColor)
      } catch (e) {} finally {
        this.$nextTick(() => {
          this.requestLoading = false
        })
      }
    },

    async handleSaveResume () {
      const searchParams = {
        content: JSON.stringify(this.editResumeList),
        themeStyleName: this.themeStyleName,
        themeColor: this.themeColor
      }
      try {
        const ops = this.resumeId ? 'update' : 'create'
        await this.$axios.post(`/gimishare/api/v1/resume/${ops}`, searchParams)
        this.$message.success(`${this.resumeId ? '更新' : '创建'}简历成功`)
        window.opener?.location.reload()
        setTimeout(() => {
          window.close()
        }, 1500)
      } catch (e) {}
    },

    async getResumeJsonTemplate () {
      const data = require('./assets/resume.json')
      this.editResumeList = data
      this.activeKeys = data.map(o => o.id)
      this.$nextTick(() => {
        this.requestLoading = false
      })
    },

    handleDeleteResumeItem (idx) {
      this.editResumeList.splice(idx, 1)
    },

    handleInsertResumeItem () {
      const id = String(Math.random()).substring(2, 12)
      this.editResumeList.push({
        id,
        component: 'OtherInfo',
        title: '自定义',
        visible: true,
        data: {
          list: [
            {
              time: [],
              rightNow: false,
              subject: '',
              other: '',
              editorHtml: '',
              visibleList: ['time', 'subject', 'other'],
              order: 'time,subject,other'
            }
          ]
        }
      })
      this.activeKeys.push(id)
    },

    handleMoveResumeItem (idx, type) {
      const target = this.editResumeList.splice(idx, 1)[0]
      this.editResumeList.splice(type === 'down' ? idx + 1 : idx - 1, 0, target)
    },

    loadResumeThemeCss () {
      this.removeResumeThemeCss()
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = `/resule-theme-style/${this.themeStyleName}.css`
      link.id = 'resume-theme-css'
      document.head.appendChild(link)
    },

    removeResumeThemeCss () {
      const link = document.querySelector('link#resume-theme-css')
      if (link) {
        document.head.removeChild(link)
      }
    },

    handleChangeTheme (theme) {
      if (theme === this.themeStyleName) return
      this.themeStyleName = theme
      this.loadResumeThemeCss()
    }
  },

  watch: {
    themeColor (newVal) {
      document.documentElement.style.setProperty('--resume-theme-color', newVal)
    }
  },

  computed: {
    ...mapState({
      userInfo: state => state.userInfo,
      siteConfig: state => state.siteConfig
    })
  },

  beforeDestroy () {
    this.removeResumeThemeCss()
    document.documentElement.style.setProperty('--resume-theme-color', '#000')
  }
}
</script>

<style scoped lang="less">
.edit-resume-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  header {
    border-bottom: 1px solid #f1f1f1;
    .c-block {
      min-width: 1320px;
      width: 80%;
      margin: 0 auto;
      height: 60px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      a {
        img {
          display: block;
          height: 42px;
        }
      }
    }
    .resume-config {
      display: flex;
      align-items: center;
      & > div {
        margin-left: 16px;
      }
      & > button {
        margin-left: 16px;
      }
    }
  }
  .content {
    width: 80%;
    margin: 0 auto;
    display: flex;
    min-width: 1320px;
    flex: 1;
    height: 0;
    padding: 10px 0;
    position: relative;
    justify-content: center;
    .show-block, .modify-block {
      width: 50%;
      border-radius: 4px;
      height: 100%;
      overflow-y: overlay;
      &::-webkit-scrollbar {
        display: none;
      }
    }
    .modify-block {
      border: 1px solid #f1f1f1;
      padding: 8px;
      ::v-deep .ant-collapse-item {
        .ant-collapse-header {
          padding: 6px 16px 6px 32px;
        }
        .ant-collapse-content {
          overflow: visible;
          &-box {
            padding: 0;
          }
        }
      }
      .edit-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        ::v-deep .edit-header-input {
          font-size: 14px;
          border: none;
          height: 26px;
          padding: 2px 4px;
          line-height: 26px;
          background: transparent;
          width: auto;
          color: #4c4c4c;
          &:hover {
            border: none;
          }
          &:focus {
            border: 1px solid #ccc;
            color: #999;
          }
        }
        .right-operate {
          display: flex;
          align-items: center;
          .ant-switch {
            margin-left: 12px;
          }
          .anticon {
            font-size: 16px;
            cursor: pointer;
            color: #4c4c4c;
            margin-left: 8px;
          }
        }
      }
    }
    .show-block {
      border: 1px dashed #f1f1f1;
      margin-left: 12px;
      print-color-adjust: exact;
      -webkit-print-color-adjust: exact;
    }
    .ant-spin-lg {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
